import 'package:family_expense/shared/constants/data_sharing_key.dart'
    as constants;
import 'package:family_expense/shared/models/system_setting.dart';
import 'package:family_expense/shared/services/system_setting_service.dart';
import 'package:flex_color_picker/flex_color_picker.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class PrimaryColorSettingView extends StatefulWidget {
  const PrimaryColorSettingView({super.key});

  @override
  State<PrimaryColorSettingView> createState() =>
      _PrimaryColorSettingViewState();
}

class _PrimaryColorSettingViewState extends State<PrimaryColorSettingView> {
  final int _maxFavoriteColorCount = 10;

  SystemSetting? _systemSetting;

  @override
  void initState() {
    super.initState();

    _getSetting();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('主色调')),
      body: _buildBody(),
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return ListView(
      children: [
        ColorPicker(
          color:
              _systemSetting?.themeSetting?.primaryColor ??
              ThemeSetting.defalutPrimaryColor,
          pickersEnabled: const <ColorPickerType, bool>{
            ColorPickerType.wheel: true,
          },
          pickerTypeLabels: const <ColorPickerType, String>{
            ColorPickerType.primary: '主要',
            ColorPickerType.accent: '色调',
            ColorPickerType.wheel: '调色盘',
          },
          width: 44,
          height: 44,
          borderRadius: 22,
          heading: Text(
            '选择颜色',
            style: Theme.of(context).textTheme.headlineSmall,
          ),
          subheading: Text(
            '选择深浅',
            style: Theme.of(context).textTheme.titleSmall,
          ),
          onColorChanged: (color) => _saveNotifyPrimaryColorChange(color),
        ),
        TextButton(
          child: Text(
            '+ 添加收藏 (${_systemSetting?.themeSetting?.favoriteColors.length ?? 0} / $_maxFavoriteColorCount)',
          ),
          onPressed: () {
            final currentFavoriteColorCount =
                _systemSetting?.themeSetting?.favoriteColors.length ?? 0;

            if (currentFavoriteColorCount >= _maxFavoriteColorCount) {
              showToast('不能添加超过 $_maxFavoriteColorCount 个');

              return;
            }

            _systemSetting!.themeSetting!.favoriteColors.add(
              _systemSetting?.themeSetting?.primaryColor ??
                  ThemeSetting.defalutPrimaryColor,
            );

            // Saves updated setting on local.
            SystemSettingService.saveSetting(_systemSetting!);

            if (mounted) {
              setState(() {});
            }
          },
        ),
        Align(
          alignment: Alignment.center,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: Wrap(
              spacing: 17.0,
              runSpacing: 17.0,
              children: _generateColorOptions(
                _systemSetting?.themeSetting?.favoriteColors,
              ),
            ),
          ),
        ),
        const SizedBox(height: 10.0),
      ],
    );
  }

  /// Generates option item for favorite color selection.
  List<Widget> _generateColorOptions(List<Color>? colors) {
    return colors
            ?.map(
              (e) => GestureDetector(
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.0, color: Colors.black),
                    color: e,
                  ),
                  height: 40.0,
                  width: 40.0,
                  child: e == _systemSetting?.themeSetting?.primaryColor
                      ? const Icon(Icons.check)
                      : null,
                ),
                onTap: () => _saveNotifyPrimaryColorChange(e),
                onLongPress: () => showConfirmDialog(
                  context,
                  '是否删除？',
                  onConfirm: () {
                    _systemSetting!.themeSetting!.favoriteColors.remove(e);

                    // Saves updated setting on local.
                    SystemSettingService.saveSetting(_systemSetting!);

                    if (mounted) {
                      setState(() {});
                    }
                  },
                ),
              ),
            )
            .toList() ??
        [];
  }

  /// Gets current system setting.
  Future<void> _getSetting() async {
    final res = await SystemSettingService.setting;

    if (mounted) {
      setState(() => _systemSetting = res);
    }
  }

  /// Saves and notifies the selected primary color change.
  void _saveNotifyPrimaryColorChange(Color color) {
    // Triggers UI build.
    if (mounted) {
      setState(() {
        _systemSetting!.themeSetting!.primaryColor = color;
      });
    }

    // Saves updated setting on local.
    SystemSettingService.saveSetting(_systemSetting!);

    final systemSettingChangeNotifier =
        DataSharing.get<SimpleChangeNotifier<SystemSetting>>(
          constants.DataSharingKey.systemSettingChangeNotifier,
        );

    // Notifies all listeners that the value has been changed.
    systemSettingChangeNotifier?.change(_systemSetting!);
  }
}
